#将文本pdf转换成图像pdf
#需要的包如下
#pip install PyMuPDF
#pip install reportlab
#pip install pillow
import os
from PIL import Image
import fitz  # PyMuPDF
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch


def find_pdf_files(directory):
    """
    遍历指定目录，返回所有PDF文件的绝对路径列表。

    :param directory: 要遍历的目录的路径
    :return: 包含所有PDF文件绝对路径的列表
    """
    print(directory)
    pdf_files = []  # 存储找到的PDF文件的绝对路径
    for root, dirs, files in os.walk(directory):
        for file in files:
            print("ok")
            if file.lower().endswith('.pdf'):  # 检查文件后缀是否为.pdf
                pdf_files.append(os.path.join(root, file))  # 添加文件的绝对路径
    return pdf_files

# 使用示例
# 假设你想要遍历的目录是"/path/to/your/directory"
# directory_path = "/path/to/your/directory"
# pdf_list = find_pdf_files(directory_path)
# print(pdf_list)



def pdf_to_images(input_pdf, output_folder):
    # 打开PDF文件
    doc = fitz.open(input_pdf)
    
    # 创建输出文件夹（如果不存在）
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    
    # 遍历每一页并将其转换为图像
    for page_num in range(len(doc)):
        page = doc.load_page(page_num)
        pix = page.get_pixmap(matrix=fitz.Matrix(300/72, 300/72))
        image_path = os.path.join(output_folder, f"page_{page_num + 1}.png")
        pix.save(image_path)
    
    doc.close()
    return [os.path.join(output_folder, f) for f in os.listdir(output_folder) if f.endswith('.png')]

def images_to_pdf(image_paths, output_pdf):
    # 获取第一张图片的尺寸
    first_image = Image.open(image_paths[0])
    img_width, img_height = first_image.size
    
    # 创建一个新的PDF文件
    c = canvas.Canvas(output_pdf, pagesize=(img_width, img_height))
    
    # 将每张图片添加到PDF中
    for image_path in image_paths:
        c.drawImage(image_path, 0, 0, width=img_width, height=img_height)
        c.showPage()
    
    c.save()

def convert_pdf_to_image_pdf(input_pdf, output_pdf):
    # 创建临时文件夹
    temp_folder = "temp_images"
    
    # 将PDF转换为图像
    image_paths = pdf_to_images(input_pdf, temp_folder)
    
    # 将图像转换为PDF
    images_to_pdf(image_paths, output_pdf)
    
    # 清理临时文件
    for image_path in image_paths:
        os.remove(image_path)
    os.rmdir(temp_folder)

# 使用示例,注意文件目录的写法，使用双反斜杠不行
directory_path = (r'C:\Users\awu\projects\tencent-ocr-analysis-master\pdf\src_pdf')
input_pdf_list =find_pdf_files(directory_path)

for input_pdf in input_pdf_list:
    output_pdf = input_pdf.replace('src', 'img')
    print(output_pdf)
    convert_pdf_to_image_pdf(input_pdf, output_pdf)
print("转换完成")